import { useRef, useState } from 'react';
import { ProTable } from '@ant-design/pro-components';
import { Button, DatePicker, Modal, message, Form, Input, Select } from 'antd';
import { PageContainer } from '@ant-design/pro-components';
import {
  querySiteList,
  redischangeSearch,
  redischangeSave,
  redischangeExecute,
  primedataReset,
} from '@/services/server';
import { EnumRedisStatus } from '@/utils/constant';
import { cloneDeep, sortBy, debounce } from 'lodash';
import type { ParamsType } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-table';
import type { PaginationProps, FormInstance } from 'antd';
import type { ActionType } from '@ant-design/pro-components';
import moment from 'moment';

import styles from './style.less';

const { confirm } = Modal;

const SensitizeManageList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [details, setDetails] = useState<any>();

  const [modalNumForm] = Form.useForm();
  const [confirmLoad, setConfirmLoad] = useState<boolean>(false);
  const [modelNumVisible, setModelNumVisible] = useState<boolean>(false);
  const [modelCodeVisible, setModelCodeVisible] = useState<boolean>(false);
  const [modalCodeForm] = Form.useForm();
  const [fromsiteOption, setFromsiteOption] = useState<any>([]);
  const [changeclusterOption, setChangeclusterOption] = useState<any>([]);

  // 提交
  const handleOperate = async (record: any, type: string) => {
    if (type === '切换') {
      confirm({
        content: `是否确认切换到当前任务？`,
        async onOk() {
          const { code, data } = await redischangeExecute({ id: record.id });
          if (code === 200 && data) {
            message.success('切换成功');
          } else {
            message.error('切换失败');
          }
          actionRef?.current?.reloadAndRest?.();
        },
        onCancel() {},
      });
      return;
    }
    if (type === '恢复') {
      modalCodeForm.setFieldsValue({
        timeRange: [
          record.executestarttime
            ? moment(new Date(record.executestarttime).getTime() - 60000)
            : null,
          record.executeendtime ? moment(new Date(record.executeendtime).getTime() + 60000) : null,
        ],
        id: record.id,
      });
      setModelCodeVisible(true);
      return;
    }
  };

  const handleChangeModel = async () => {
    const { code, data } = await querySiteList({});
    if (code === 200 && data) {
      const firstEntry: any = Object.entries(cloneDeep(data)).slice(-1)[0];
      const firstEntryBro = Object.entries(firstEntry[1].ips)[1];

      setDetails(data);
      setModelNumVisible(true);
      // 收集 分组和站点list
      const arr: any[] = [];
      const list: any[] = [];
      Object.keys(data).forEach((key, index) => {
        arr.push({
          label: key,
          value: key,
        });
        if (index === 0 && key && data[key]) {
          Object.keys(data[key].ips).forEach((item) => {
            list.push({
              label: item,
              value: item,
            });
          });
          modalNumForm.setFieldsValue({
            changecluster: firstEntry[0],
            fromsite: data[key].currentSite,
            tosite: firstEntryBro[0],
            curValue: data[key].currentIp,
            changeValue: data[key].ips.TEST || '',
          });
        }
      });
      setChangeclusterOption(arr.reverse());
      setFromsiteOption(sortBy(list, 'label'));
    }
  };

  const columns: ProColumns<API.ProfileListItem>[] = [
    // 表单
    {
      title: 'Redis站点',
      dataIndex: 'fromsite',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    // 表格
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      ellipsis: true,
      width: 60,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '当前站点',
      dataIndex: 'fromsite',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '目标站点',
      dataIndex: 'tosite',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '目标Redis分组',
      dataIndex: 'changecluster',
      ellipsis: true,
      width: 200,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      ellipsis: true,
      width: 100,
      align: 'center',
      hideInSearch: true,
      valueEnum: EnumRedisStatus,
    },
    {
      title: '更新时间',
      dataIndex: 'lastupdatetime',
      ellipsis: true,
      width: 120,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '执行开始时间',
      dataIndex: 'executestarttime',
      ellipsis: true,
      width: 120,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '执行结束时间',
      dataIndex: 'executeendtime',
      ellipsis: true,
      width: 120,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 80,
      align: 'center',
      hideInSearch: true,
      fixed: 'right',
      render(_, record) {
        return (
          <div key={record.id}>
            {record.status === 1 ? (
              record.changecluster === 'redis4Cluster' ? (
                <a onClick={() => handleOperate(record, '恢复')}>恢复</a>
              ) : null
            ) : (
              <a onClick={() => handleOperate(record, '切换')}>切换</a>
            )}
          </div>
        );
      },
    },
  ];

  // 获取列表
  const getPromotionList = async (params: ParamsType) => {
    const { current, ...rest } = params;
    const param: any = {
      pageNo: current || 1,
      pageSize: params.pageSize || 10,
      ...rest,
    };

    const { code, data } = await redischangeSearch(param);
    if (code === 200 && data) {
      const { rows, totalCount, pageSize, pageNo } = data;
      return {
        total: totalCount,
        pageSize,
        current: pageNo,
        data: rows,
      };
    }
    return {};
  };

  const showTotal: PaginationProps['showTotal'] = (t) => `共 ${t} 条`;

  const handleNumCancel = () => {
    setModelNumVisible(false);
    modalNumForm.resetFields();
  };

  const handleNumOK = (type: string) => {
    modalNumForm.validateFields().then(async (values) => {
      setConfirmLoad(true);

      const params = {
        fromsite: values.fromsite,
        tosite: values.tosite,
        changecluster: values.changecluster,
      };

      const fetchApi = type === '暂存' ? redischangeSave : redischangeExecute;
      const { code, data } = await fetchApi(params);

      if (code === 200) {
        message.success('操作成功');
        modalNumForm.resetFields();
        setModelNumVisible(false);
        actionRef?.current?.reloadAndRest?.();
      } else {
        message.error('操作失败');
        modalNumForm.resetFields();
        setModelNumVisible(false);
        actionRef?.current?.reloadAndRest?.();
      }
      setConfirmLoad(false);
    });
  };

  // 创建一个防抖后的点击事件处理函数
  const debouncedFunction = (type: string) =>
    debounce(() => {
      // 处理点击事件的逻辑，可以使用传入的参数
      handleNumOK(type);
    }, 300);

  const handleCodeCancel = () => {
    setModelCodeVisible(false);
    modalCodeForm.resetFields();
  };

  const handleCodeOK = () => {
    modalCodeForm.validateFields().then(async (values) => {
      const { timeRange } = values;
      if (!timeRange[0] || !timeRange[1]) {
        message.error('执行时间不得为空');
        return;
      }
      const difference = timeRange[1].diff(timeRange[0], 'seconds');
      if (difference > 86400) {
        message.error('时间范围不能超过24小时！');
        return;
      }

      const { code, data } = await primedataReset({
        startTime: moment(timeRange[0]).format('YYYY-MM-DD HH:mm:ss'),
        endTime: moment(timeRange[1]).format('YYYY-MM-DD HH:mm:ss'),
        // id: values.id,
      });
      if (code === 200) {
        message.success('恢复成功');
        modalCodeForm.resetFields();
        setModelCodeVisible(false);
        actionRef?.current?.reloadAndRest?.();
      } else {
        message.error('恢复失败');
        modalCodeForm.resetFields();
        setModelCodeVisible(false);
        actionRef?.current?.reloadAndRest?.();
      }
    });
  };

  const handleSelectCluster = (e: string) => {
    const tositeBro = modalNumForm.getFieldValue('tosite');
    modalNumForm.setFieldsValue({
      changecluster: e,
      fromsite: details[e].currentSite,
      tosite: tositeBro,
      curValue: details[e].currentIp,
      changeValue: details[e].ips[tositeBro] || '',
    });
  };

  const handleSelectTosite = (e: string) => {
    const changeclusterBro = modalNumForm.getFieldValue('changecluster');
    modalNumForm.setFieldsValue({
      tosite: e,
      changeValue: details[changeclusterBro].ips[e] || '',
    });
  };

  return (
    <PageContainer>
      <div className={styles['form-body']}>
        <ProTable<API.RedischangeListItem>
          manualRequest={true}
          rowKey="id"
          columns={columns}
          actionRef={actionRef}
          formRef={formRef}
          request={getPromotionList}
          options={false}
          search={{
            optionRender: (searchConfig, props, dom) => [...dom],
          }}
          toolBarRender={() => [
            <Button type="primary" key="add" onClick={handleChangeModel}>
              切换
            </Button>,
          ]}
          scroll={{ x: 800 }}
          pagination={{
            showSizeChanger: true,
            size: 'small',
            showTotal,
            showQuickJumper: true,
            defaultPageSize: 10,
          }}
        />
        <Modal
          title="切换Redis"
          width={520}
          open={modelNumVisible}
          onCancel={handleNumCancel}
          confirmLoading={confirmLoad}
          footer={null}
        >
          <Form
            labelCol={{ span: 6 }}
            form={modalNumForm}
            initialValues={{
              changecluster: '',
              fromsite: '',
              tosite: '',
              curValue: '',
              changeValue: '',
            }}
          >
            <Form.Item label="Redis分组" name="changecluster">
              <Select
                options={changeclusterOption}
                onChange={(e) => {
                  handleSelectCluster(e);
                }}
              />
            </Form.Item>
            <Form.Item label="当前站点" name="fromsite">
              <Select disabled options={fromsiteOption} />
            </Form.Item>
            <Form.Item label="目标站点" name="tosite">
              <Select
                options={fromsiteOption}
                onChange={(e) => {
                  handleSelectTosite(e);
                }}
              />
            </Form.Item>
            <Form.Item label="当前配置" name="curValue">
              <Input.TextArea rows={4} placeholder="" disabled />
            </Form.Item>
            <Form.Item label="目标配置" name="changeValue">
              <Input.TextArea rows={4} placeholder="" disabled />
            </Form.Item>
          </Form>
          <div style={{ display: 'flex', justifyContent: 'center' }}>
            <Button
              type="primary"
              key="sun"
              onClick={() => handleNumOK('暂存')}
              style={{ marginLeft: 28, marginRight: 28 }}
            >
              暂存
            </Button>
            <Button
              loading={confirmLoad}
              type="primary"
              key="moon"
              onClick={debouncedFunction('确认切换')}
            >
              确认切换
            </Button>
          </div>
        </Modal>

        <Modal
          title="数据恢复"
          width={520}
          open={modelCodeVisible}
          onOk={handleCodeOK}
          onCancel={handleCodeCancel}
          confirmLoading={confirmLoad}
        >
          <Form
            labelCol={{ span: 6 }}
            form={modalCodeForm}
            initialValues={{
              timeRange: [null, null],
              id: '',
            }}
          >
            <Form.Item label="id" name="id" hidden>
              <Input />
            </Form.Item>

            <Form.Item
              label="时间范围"
              name="timeRange"
              rules={[{ required: true, message: '不得为空' }]}
            >
              <DatePicker.RangePicker showTime format="YYYY-MM-DD HH:mm:ss" />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </PageContainer>
  );
};

export default SensitizeManageList;
